﻿using QQExpression.Utils.Currency;
using QQExpression.Utils.Helper;
using QQExpression.Utils.Type;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QQExpression.Utils
{
    class QQhelper
    {
        /// <summary>
        /// 异步读取文件，不阻塞进程
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public async Task<string> ReadFileAsync(string FileName, RichTextBox richTextBox1)
        {


            return await Task.Run<string>(() =>
            {
                return ReadFile(FileName,richTextBox1);
            });
        }



        /// <summary>
        ///  读取文件
        /// </summary>
        /// <param name="FileName"></param>
        public static string ReadFile(string FileName, RichTextBox richTextBox1)
        {
            if (FileName == "")
                return "";
            String Hexstr = new HexConvertHelper().FileToHex(FileName);

            String FloderPath = GetSavePath(FileName);
            foreach (Match SingeleMatch in Regex.Matches(Hexstr, "(89504e47.*?49454e44ae426082|ffd8ff.*?fffd9|47494638.*?003b)"))
            {
              
                AutoSaveFile(SingeleMatch.Value, FloderPath, richTextBox1);
            }
            return FloderPath;
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="Filevalue"></param>
        /// <param name="FloderPath"></param>
        private static void AutoSaveFile(string Filevalue, String FloderPath, RichTextBox richTextBox1)
        {
            string FileExt = ".jpg";
            if (Filevalue.IndexOf("89504e47") == 0)
                FileExt = ".png";
            else if (Filevalue.IndexOf("47494638") == 0)
                FileExt = ".gif";
            String SavePath = FloderPath + string.Format("{0}{1}", DateTime.Now.ToFileTime(), FileExt);
            Console.WriteLine(SavePath);
            richTextBox1.AppendText("\r\n提取："+SavePath);
            richTextBox1.Select(richTextBox1.TextLength, 0);
            richTextBox1.ScrollToCaret();
            new ByteHelper().ByteToFile(new HexConvertHelper().HexStrTobyte(Filevalue), SavePath);

        }

        /// <summary>
        /// 获取保存文件夹的路径
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        private static string GetSavePath(string FileName)
        {
            string QQFaceName = TextHelper.ReplaceBadChar(FileHelper.GetFileNameWithoutExtension(FileName));
            String SavePath = StaticValue.TempPath;
            if (QQFaceName != "")
                SavePath = SavePath + TextHelper.ReplaceBadChar(QQFaceName) + "\\";

            Console.WriteLine("创建文件夹" + FloderHelper.FloderExits(SavePath, true));

            return SavePath;

        }
    }
}
